import { createStore } from 'vuex'
import useStorage from "@/utils/useStorage";
import { http} from "@/api";
import {defaultMockMenu} from "@/utils/common";
const storage = useStorage()

export default createStore({
  state: {
    token: storage.getItem('token') || '',
    userInfo: storage.getItem('userInfo') || {},
    menuList:  defaultMockMenu,
  },
  getters: {
    token: (state) => state.token,
      userName: (state) => state.userInfo.chinese_name || '',
      userInfo: (state) => state.userInfo || {},
    menuList: (state) => state.menuList,
  },
  mutations: {
       setToken(state, token) {
            state.token = token
       },
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo
        },
        setMenuList(state, menuList) {
             state.menuList = menuList
        },
  },
  actions: {
    login({ commit }, data) {
      return new Promise((resolve, reject) => {
        http.login(data).then(res => {
            const { token } = res.data
            console.log(res.data)
            storage.setItem('token', token)
            storage.setItem('userInfo', res.data)
            commit('setToken', token)
            commit('setUserInfo', res.data)
            resolve(res)
        }).catch(err => {
            reject(err)
        })
      })
    },
    resetState({ commit }) {
      return new Promise((resolve, reject) => {
        storage.removeItem('token')
        storage.removeItem('userInfo')
        storage.removeItem('menuList')
        commit('setToken', '')
        commit('setUserInfo', {})
        commit('setMenuList', [])
        resolve()
      })
    },
  },
  modules: {
  }
})
